<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <!-- scope.row可以获取到所有的数据 -->
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="getEditForm(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- 分页导航区域
      @size-change(pagesize改变时触发)
      @current-change(页码发生改变时触发)
      :current-page(设置当前页码)
      :page-size(设置每页的数据条数)
      :total(设置总页数)-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="70%"
      @close="closeAddDialogVisible"
    >
      <!-- 添加用户信息 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息用户"
      :visible.sync="editDialogVisible"
      width="70%"
      @close="closeEditForm"
    >
      <!-- 添加用户信息 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="RolesDialogVisible"
      width="30%"
      @close="closeRoles"
    >
      <div>
        <p>当前的用户：{{rolesinfo.username}}</p>
        <p>当前的角色：{{rolesinfo.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="roleNameId" placeholder="请选择角色">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱验证
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入邮箱'))
      }
    }
    // 自定义手机号验证
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入手机号'))
      }
    }
    return {
      // 获取用户信息的查询参数
      queryInfo: {
        // 查询内容
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页展示多少条数据
        pagesize: 2
      },
      userList: [],
      // 条目数
      total: 0,
      // 显示与隐藏添加用户弹出框
      addDialogVisible: false,
      // 获取表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, message: '手机号格式不正确，请重新输入', trigger: 'blur' }
        ]
      },
      // 显示与隐藏修改用户弹出框
      editDialogVisible: false,
      // 获取查询用户信息
      editForm: {},
      // 验证邮箱和手机号
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, message: '手机号格式不正确，请重新输入', trigger: 'blur' }
        ]
      },
      // 分配角色对话框的显示与隐藏
      RolesDialogVisible: false,
      // 获取要分配角色的信息
      rolesinfo: '',
      // 新角色的id
      roleNameId: '',
      // 获取所有角色列表
      rolesList: []
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表信息
    async getUserList() {
      const { data: res } = await this.axios.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.msg.error(res.meta.msg)
      // 用户列表数据
      this.userList = res.data.users
      // 总条目数
      this.total = res.data.total
    },
    // 通过监听switch的change事件来修改用户的状态
    async changeState(scope) {
      const { data: res } = await this.axios.put(`users/${scope.id}/state/${scope.mg_state}`)
      if (res.meta.status !== 200) {
        scope.mg_state = !scope.mg_state
        return this.msg('修改用户状态失败')
      }
      this.msg('更新用户状态成功')
    },
    // 监听pagesize发生变化，默认第一个参数就是新值
    handleSizeChange(num) {
      this.queryInfo.pagesize = num
      this.getUserList()
    },
    // 监听pagenum发生变化，默认第一个参数就是新值
    handleCurrentChange(current) {
      this.queryInfo.pagenum = current
      this.getUserList()
    },
    // 弹出框关闭后重置表单
    closeAddDialogVisible() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击提交进行表单预验证
    submitForm() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.axios.post('users', this.addForm)
          if (res.meta.status !== 201) return this.msg.error('添加用户失败')
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 点击打开弹出框，渲染数据
    async getEditForm(id) {
      this.editDialogVisible = true
      const { data: res } = await this.axios.get('users/' + id)
      if (res.meta.status !== 200) return this.msg.error('获取用户信息失败')
      this.editForm = res.data
    },
    // 表单预验证，提交修改信息
    submitEditForm() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.axios.put('users/' + this.editForm.id, this.editForm)
          if (res.meta.status !== 200) return this.msg.error('更新用户信息失败')
          this.editDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 关闭修改表单弹出框后重置表单
    closeEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击删除用户
    async deleteUser(id) {
      // this.cof返回的是一个Promise对象
      const result = await this.cof('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 捕捉错误并且返回这个错误
      // 点击取消返回一个cancel字符串
      // 点击确认返回一个confirm字符串
      if (result !== 'confirm') {
        return this.msg('你取消了删除')
      }
      const { data: res } = await this.axios.delete('users/' + id)
      if (res.meta.status !== 200) return this.msg.error('删除用户失败')
      this.msg('删除用户成功')
      this.getUserList()
    },
    // 点击显示分配角色对话框
    async setRoles(roles) {
      this.rolesinfo = roles
      const { data: res } = await this.axios.get('roles')
      if (res.meta.status !== 200) return this.msg.error('获取用户角色信息失败')
      this.rolesList = res.data
      this.RolesDialogVisible = true
    },
    // 点击确认修改用户角色信息
    async submitRoles() {
      const { data: res } = await this.axios.put(`users/${this.rolesinfo.id}/role`, { rid: this.roleNameId })
      if (res.meta.status !== 200) return this.msg.error('修改用户角色信息失败')
      this.msg('修改用户角色成功')
      this.getUserList()
      this.RolesDialogVisible = false
    },
    // 对话框关闭后重置下拉框
    closeRoles() {
      this.rolesinfo = ''
      this.rolesList = []
    }
  }
}
</script>

<style scoped lang="less">

</style>
